﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace XingLucifer.Devices.Inits
{
    public class FeatherInjectionPump : DevicePing
    {
        public FeatherInjectionPump(Action<string> action) : base(XingLucifer.IBase.Enums.DeviceTypes.NJ_FINS_PLC, action)
        {
        }
        string[] _ip;
        private string _sourceIP;
        public override bool Init(string? sourceIP, string ip, string? dns, int port)
        {
            _sourceIP = sourceIP;
            if (Login_CP1WCIF41_Module(sourceIP))
            {
                _ip = ip.Split('.');
                if (CP1WCIF41_Module(sourceIP, _ip[2], _ip[3], "%B4%AB%CB%CD"))
                {
                    return true;
                }
                else
                {
                    _action?.Invoke("配置注液泵失败");
                }
            }
            else
            {
                _action?.Invoke("登录注液泵失败");
            }
            return false;
        }

        public override bool Ping(string? ip = null)
        {
            return base.Ping(ip);
        }

        public override bool Reboot()
        {
            bool bl = CP1WCIF41_Module(_sourceIP, _ip[2], _ip[3], "%D6%D8%C6%F4");
            System.Threading.Thread.Sleep(10000);
            return bl;
        }

        /// <summary>
        /// 重启与配置网络模块
        /// </summary>
        /// <param name="url">链接</param>
        private static bool CP1WCIF41_Module(string ip, string ip3, string ip4, string command)
        {
            try
            {
                HttpWebRequest request = WebRequest.CreateHttp($"http://{ip}/P1");
                request.Method = "POST";
                request.Accept = @"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";
                request.KeepAlive = false;
                request.UserAgent = @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36 Edg/94.0.992.50";
                request.Host = ip;
                request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
                request.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
                request.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
                request.Headers.Add(HttpRequestHeader.Connection, "keep-alive");
                request.Referer = $"http://{ip}/C21.htm";
                string data = $"IP1=192&IP2=168&IP3={ip3}&IP4={ip4}&MSK1=255&MSK2=255&MSK3=255&MSK4=0&NODE={ip4}&FUDP=0&FTCP=0&ACNV=AUTOD&FUDPOPT=FUDPNOOPT&BCAST=43BSD&COMMAND={command}";//%D6%D8%C6%F4
                byte[] bytes = System.Text.Encoding.ASCII.GetBytes(data);
                request.ContentLength = bytes.Length;
                using (System.IO.Stream stream = request.GetRequestStream())
                {
                    stream.Write(bytes, 0, bytes.Length);
                }
                var response = request.GetResponse();
                int length = 0;
                byte[] byte1 = new byte[2048];
                using (Stream stream = response.GetResponseStream())
                {
                    length = stream.Read(byte1, 0, 2048);
                }
                string str = System.Text.Encoding.Default.GetString(byte1.Take(length).ToArray());
                return !str.Contains("INPUT TYPE=\"submit\"");
            }
            catch (Exception ex)
            {
                return ex.Message == "An error occurred while sending the request.";
            }
        }

        /// <summary>
        /// 登录模块
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        private static bool Login_CP1WCIF41_Module(string ip)
        {
            try
            {
                HttpWebRequest request = WebRequest.CreateHttp($"http://{ip}/P0");
                request.Method = "POST";
                request.Accept = @"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";
                request.KeepAlive = false;
                request.UserAgent = @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36 Edg/94.0.992.50";
                request.Host = ip;
                request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
                request.Headers.Add(HttpRequestHeader.AcceptLanguage, "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
                request.Headers.Add(HttpRequestHeader.ContentType, "application/x-www-form-urlencoded");
                request.Headers.Add(HttpRequestHeader.Connection, "keep-alive");
                request.Referer = $"http://{ip}/c00.htm";
                string data = "PASSCN=ETHERNET&COMMAND=%B5%C7%C2%BD";
                byte[] bytes = System.Text.Encoding.ASCII.GetBytes(data);
                request.ContentLength = bytes.Length;
                using (System.IO.Stream stream = request.GetRequestStream())
                {
                    stream.Write(bytes, 0, bytes.Length);
                }
                var response = request.GetResponse();
                int length = 0;
                byte[] byte1 = new byte[2048];
                using (Stream stream = response.GetResponseStream())
                {
                    length = stream.Read(byte1, 0, 2048);
                }
                string str = System.Text.Encoding.Default.GetString(byte1.Take(length).ToArray());
                return str.Contains("FRAME SRC=\"C10.htm\"");
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
